package com.zw.yzk.kabu.adapter;

import android.content.Context;
import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.zw.yzk.kabu.R;
import com.zw.yzk.kabu.constant.ActivityConstant;
import com.zw.yzk.kabu.model.CosplayModel;
import com.zw.yzk.kabu.utils.CircleTransform;
import com.zw.yzk.kabu.utils.PhoneUtils;
import com.zw.yzk.kabu.utils.QNImageUtils;
import com.zw.yzk.kabu.utils.StringUtils;
import com.zw.yzk.kabu.view.activity.CosplayDetailsActivity;
import com.zw.yzk.kabu.view.activity.HomePageActivity;
import com.zw.yzk.kabu.view.activity.TopicListActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by zhanwei on 2016/12/28.
 */

public class CosplayListAdapter extends RecyclerView.Adapter<CosplayListAdapter.Holder> {

    private List<CosplayModel> modelList;
    private Context context;

    public CosplayListAdapter(List<CosplayModel> list) {
        modelList = new ArrayList<>();
        if (list != null) {
            modelList.addAll(list);
        }
    }

    public void refresh(List<CosplayModel> list) {
        modelList.clear();
        if (list != null) {
            modelList.addAll(list);
            notifyDataSetChanged();
        }
    }

    public void add(List<CosplayModel> list) {
        if (list != null) {
            int startPosition = modelList.size();
            modelList.addAll(list);
            notifyItemRangeInserted(startPosition, list.size());
        }
    }

    public List<CosplayModel> getTotalList() {
        return modelList;
    }

    @Override
    public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (context == null) {
            context = parent.getContext();
        }
        View view = LayoutInflater.from(context).inflate(R.layout.recycler_item_cosplay_list, parent, false);

        return new Holder(view);
    }

    @Override
    public void onBindViewHolder(Holder holder, int position) {
        final CosplayModel model = modelList.get(position);
        holder.nickName.setText(model.getPublisher());
        if (TextUtils.isEmpty(model.getPublishAddress())) {
            holder.location.setText(context.getResources().getString(R.string.unknown_address));
        } else {
            holder.location.setText(model.getPublishAddress());
        }

        holder.competition.setVisibility(model.isCompetition() ? View.VISIBLE : View.GONE);
        holder.time.setText(model.getPublishTime());
        //设置文本样式
        SpannableString string = colorTextAndClickableWithPattern(
                model.getMessage(), StringUtils.DIVIDE_STRING_PATTERN1,
                ContextCompat.getColor(context, R.color.gold), context);
        SpannableString text = colorTextAndClickableWithPattern(string, StringUtils.DIVIDE_STRING_PATTERN2,
                ContextCompat.getColor(context, R.color.gold), context);
        holder.remark.setText(text);
        holder.remark.setMovementMethod(LinkMovementMethod.getInstance());
        holder.remark.setHighlightColor(ContextCompat.getColor(context, R.color.transparent));
        if (TextUtils.isEmpty(model.getMessage())) {
            holder.remark.setVisibility(View.GONE);
        }
        holder.likeCount.setText(String.valueOf(model.getPraiseCount()));
        holder.likeCount.setChecked(model.isPraise());
        holder.collect.setChecked(model.isCollected());
        holder.commentCount.setText(String.valueOf(model.getCommentCount()));

        Glide.with(context)
                .load(model.getPublisherHeadUrl())
                .centerCrop()
                .error(R.drawable.ic_default_head)
                .placeholder(R.drawable.ic_default_head)
                .transform(new CircleTransform(context))
                .into(holder.head);

        Glide.with(context)
                .load(QNImageUtils.getThumbnail(model.getCosUrl(), PhoneUtils.getScreenWidth(context), PhoneUtils.getScreenWidth(context)))
                .centerCrop()
                .error(R.drawable.im_default)
                .override(PhoneUtils.getScreenWidth(context), PhoneUtils.getScreenWidth(context))
                .into(holder.content);

        holder.head.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, HomePageActivity.class);
                intent.putExtra(ActivityConstant.HOME_PAGE_ID, model.getPublisherId());
                context.startActivity(intent);
            }
        });

        holder.content.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, CosplayDetailsActivity.class);
                intent.putExtra(ActivityConstant.OPEN_COS_DETAIL_NAME, model.getPublisher());
                intent.putExtra(ActivityConstant.OPEN_COS_DETAIL_ID, model.getId());
                context.startActivity(intent);
            }
        });

        holder.commentCount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, CosplayDetailsActivity.class);
                intent.putExtra(ActivityConstant.OPEN_COS_DETAIL_NAME, model.getPublisher());
                intent.putExtra(ActivityConstant.OPEN_COS_DETAIL_ID, model.getId());
                context.startActivity(intent);
            }
        });

        holder.likeCount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                model.setPraise(!model.isPraise());
                if (listener != null) {
                    listener.onPraiseClicked(model);
                }
            }
        });

        holder.collect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                model.setCollected(!model.isCollected());
                if (listener != null) {
                    listener.onCollectClicked(model);
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return modelList.size();
    }

    /**
     * 给特定格式文本着色并添加点击事件
     *
     * @param source  源文本
     * @param pattern 格式
     * @param color   颜色
     * @return SpannableString
     */
    private SpannableString colorTextAndClickableWithPattern(String source, String pattern, int color, Context context) {
        if(TextUtils.isEmpty(source)) {
            return new SpannableString("");
        }
        SpannableString spanText = new SpannableString(source);
        List<String> patternResult = StringUtils.divideString(source, pattern);
        String remainString = source;
        int realStart = 0;
        for (String str : patternResult) {
            realStart += remainString.indexOf(str);
            spanText.setSpan(new ClickSpan(context), realStart, realStart + str.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            spanText.setSpan(new ForegroundColorSpan(color), realStart, realStart + str.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
            remainString = remainString.substring(remainString.indexOf(str) + str.length());
            realStart += str.length();
        }

        return spanText;
    }

    /**
     * 给特定格式文本着色并添加点击事件
     *
     * @param source  源文本
     * @param pattern 格式
     * @param color   颜色
     * @return SpannableString
     */
    private SpannableString colorTextAndClickableWithPattern(SpannableString source, String pattern, int color, Context context) {
        if(source == null) {
            return new SpannableString("");
        }
        SpannableString spanText = source;
        List<String> patternResult = StringUtils.divideString(source.toString(), pattern);
        String remainString = source.toString();
        int realStart = 0;
        for (String str : patternResult) {
            realStart += remainString.indexOf(str);
            spanText.setSpan(new ClickSpan(context), realStart, realStart + str.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            spanText.setSpan(new ForegroundColorSpan(color), realStart, realStart + str.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
            remainString = remainString.substring(remainString.indexOf(str) + str.length());
            realStart += str.length();
        }

        return spanText;
    }

    public static class Holder extends RecyclerView.ViewHolder {
        @Bind(R.id.head)
        ImageView head;
        @Bind(R.id.nick_name)
        TextView nickName;
        @Bind(R.id.publish_address)
        TextView location;
        @Bind(R.id.time)
        TextView time;
        @Bind(R.id.message)
        TextView remark;
        @Bind(R.id.content_url)
        ImageView content;
        @Bind(R.id.like)
        CheckBox likeCount;
        @Bind(R.id.comment)
        CheckBox commentCount;
        @Bind(R.id.collect)
        CheckBox collect;
        @Bind(R.id.competition)
        ImageView competition;

        public Holder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    public interface OnItemClickedListener {
        void onPraiseClicked(CosplayModel model);

        void onCollectClicked(CosplayModel model);
    }

    public OnItemClickedListener listener;

    public void setOnItemClickedListener(OnItemClickedListener listener) {
        this.listener = listener;
    }

    private static class ClickSpan extends ClickableSpan {

        private Context context;

        public ClickSpan(Context context) {
            this.context = context;
        }

        @Override
        public void onClick(View widget) {
            try {
                TextView tv = (TextView) widget;
                String s = tv.getText().subSequence(tv.getSelectionStart(),
                        tv.getSelectionEnd()).toString().replace("#", "");
                if(s.startsWith("@")) {
                    HomePageActivity.startHomePageActivity(context, 0, s.substring(1));
                } else {
                    TopicListActivity.startTopicActivity(context, s);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        @Override
        public void updateDrawState(TextPaint ds) {
            ds.setColor(ds.linkColor);
            ds.setUnderlineText(false);    //去除超链接的下划线
        }
    }
}
